package com.youwu.weather.service;

import com.youwu.weather.vo.WeatherType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class WeatherDataCollectionServiceImpl implements WeatherDataCollectionService {

    private static Logger logger = LoggerFactory.getLogger(WeatherDataCollectionServiceImpl.class);
    private static final String WEATHER_URI = "https://free-api.heweather.net/s6/weather/";
    private static final String KEY = "1fba98d5c3954585a4571eb4d1c179ae";
    private static final long TIME_OUT = 1800L;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void syncDataByCity(WeatherType weatherType, String city) {
        String uri = WEATHER_URI + weatherType.type + "?location=" + city + "&key=" + KEY;
        this.saveWeatherData(uri);
    }

    private void saveWeatherData(String uri) {
        String key = uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }

        // 数据写入缓存中
        ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);
    }
}
